<template>
    <div class="user-service-form">
      <h2>提交售后单</h2>
      <el-form :model="serviceForm" ref="formRef" label-width="100px">
        <el-form-item label="售后类型" prop="ticketType" :rules="{ required: true, message: '请选择售后类型', trigger: 'change' }">
          <el-select v-model="serviceForm.ticketType" placeholder="请选择">
            <el-option label="产品故障" value="产品故障"></el-option>
            <el-option label="退换货" value="退换货"></el-option>
            <el-option label="维修服务" value="维修服务"></el-option>
            <el-option label="技术咨询" value="技术咨询"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="问题描述" prop="description" :rules="{ required: true, message: '请输入问题描述', trigger: 'blur' }">
          <el-input type="textarea" v-model="serviceForm.description" :rows="5" placeholder="请详细描述您遇到的问题"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交售后单</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive } from 'vue'
  import { submitServiceTicket } from '../../api'
  import { useUserStore } from '../../stores/user'
  import { ElMessage } from 'element-plus'
  
  const userStore = useUserStore()
  const formRef = ref(null)
  const serviceForm = reactive({
    username: userStore.username,
    ticketType: '',
    description: ''
  })
  
  const handleSubmit = () => {
    formRef.value.validate(async (valid) => {
      if (valid) {
        try {
          const response = await submitServiceTicket(serviceForm)
          if (response.data.success) {
            ElMessage.success(response.data.message)
            resetForm()
          } else {
            ElMessage.error(response.data.message || '提交失败！')
          }
        } catch (error) {
          ElMessage.error('请求出错！')
          console.error('Failed to submit ticket:', error)
        }
      } else {
        ElMessage.error('请填写完整并正确的信息！')
        return false
      }
    })
  }
  
  const resetForm = () => {
    formRef.value.resetFields()
  }
  </script>
  
  <style scoped>
  .user-service-form {
    padding: 20px;
    max-width: 800px;
    margin: 0 auto;
  }
  </style>